import sqlite3
import datetime


class StockOB:
    def __init__(self):
        self.db_path = "./data.db"

    def execute_sql(self, sql):
        try:
            # 创建数据连接
            conn = sqlite3.connect(self.db_path)
            cur = conn.cursor()
            cur.execute(sql)
            # 如果sql是查询操作就返回查询的结果
            if sql.strip().startswith("select"):
                data = cur.fetchall()
                conn.commit()
                conn.close()
                return {
                    "status": 200,
                    "msg": "sql执行成功！",
                    "data": data
                }
            # 否则就执行sql
            else:
                conn.commit()
                conn.close()
                return {
                    "status": 200,
                    "msg": "sql执行成功！"
                }
        except Exception as e:
            return {
                "status": 400,
                "msg": str(e)
            }

    def insert_overwrite_token(self, token):
        """
        sqlite 没有insert overwrite 操作，所以用先删除在插入的方法
        """
        # 清空token
        sql1 = "delete from token;"
        sql1_result = self.execute_sql(sql1)
        # 写入新的token
        sql2 = f"insert into token (token) values ('{token}');"
        sql2_result = self.execute_sql(sql2)
        # 两个sql都执行成功
        if sql1_result["status"] == 200 and sql2_result["status"] == 200:
            return {
                "status": 200,
                "msg": "重置token成功！"
            }
        # 有一个没有成功，返回sql执行失败的信息
        else:
            return {
                "status": 400,
                "msg": "清空表：" + sql1_result["msg"] + "插入数据：" + sql2_result["msg"]
            }

    def select_token(self):
        """
        查询token函数
        """
        sql = "select token from token"
        result = self.execute_sql(sql)
        if result['status'] == 200:
            ts_token = result["data"][0][0]
            return {
                "status": 200,
                "ts_token": ts_token
            }
        # 如果不为200，返回执行sql的保存信息
        return result


if __name__ == '__main__':
    # 修改默认的token
    db = StockOB()
    ts_token = "fb8c70426f1d5aea174eefd32219ab3b752bf5e8a89481a79450153b"
    print(db.insert_overwrite_token(ts_token))
    pass
